package cn.yili12.business.service;

import cn.yili12.business.cache.FriendCache;
import cn.yili12.business.entity.MessageDb;
import cn.yili12.business.repository.MessageRepository;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageRepository repository;
    @Autowired
    private UserService userService;
    @Autowired
    private FriendCache friendCache;

    public void save(MessageDb messageDb) {
        repository.save(messageDb);
        if (!friendCache.have(messageDb.getToUser(), messageDb.getFromUser())) {
            userService.saveOrUpdateFriend(Long.valueOf(messageDb.getToUser()), Long.valueOf(messageDb.getFromUser()));
        }
    }

    @Transactional
    public void updateRead(String no) {
        repository.updateRead(new Date(), 1, no);
    }

    @Transactional
    public void updateRead(List<String> nos) {
        repository.updateBatchRead(new Date(), 1, nos);
    }

    public Page<MessageDb> findHistory(String userId, String friendId, int pageNo, int pageSize) {
        return repository.findHistory(userId, friendId, PageRequest.of(pageNo - 1, pageSize));
    }
}
